#/usr/local/bin/python
#!coding:utf-8
import ConfigParser
import MySQLdb
import logging
import os,sys,getopt
import datetime
import time
#
#getsize
#check_sync



logger = logging.getLogger()
logging.basicConfig(level=logging.INFO,
                format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                datefmt='%a, %d %b %Y %H:%M:%S',filename='run.log',filemode='a+')
config_read = ConfigParser.RawConfigParser()
config_read.read('rsync.ini')






def usage():
	print("logsync -d day	r_ip r_name")
	print("logsync	r_ip r_name (default yesterday)")

def getsize():
	global todir
	return os.popen("du -sm "+todir+"/"+"|cut -f1").read()
def is_exists():
	global todir,config_read,logging
	#判断目标文件夹地址是否存在	
	if(os.path.exists(todir)):
		pass
	else:
		logging.info(todir+"not exist")
		exit()
#检查sync进程是否结束
def check_sync():
	global r_ip,r_name,if_sync,log_sw,logging
	if if_sync==1:
		logging.info("sync process is "+str(if_sync))
	if_sync=int(os.popen("ps -ef|grep "+r_ip + "::" + r_name+"|grep -v grep |wc -l").read().strip())
	print("ps -ef|grep "+r_ip + "::" + r_name+"|grep -v grep |wc -l"+"\n")
	print(if_sync)
	if(log_sw!=if_sync):
		logging.info("sync process is "+str(if_sync))
		log_sw=if_sync
def ready4sync():
	global r_ip,r_name,yes_time,sync_list,sync_file,cur,hostmod,today,yes_time_nyr
	#获取文件列表
	cur_list = os.popen("rsync -r " + r_ip + "::" + r_name+"| grep  " + yes_time_nyr).readlines()
	for line in cur_list:
		line = line.strip().split()
		filesize=line[1]
		filename=line[4]
		cur.execute('insert into logtoday values("'+hostmod+'","'+filename+'",'+filesize+',"'+today+'")')
		sync_list.append(filename)
	with open(sync_file, 'w') as f:
		for l in sync_list:
			f.writelines(l + "\n") 
	f.close()
def do_sync():
	global sync_file,r_ip,r_name,todir
	sync_cmd = "/usr/bin/rsync -avz --files-from=" + sync_file + " " + r_ip + "::" + r_name + " " + todir
	os.popen(sync_cmd+"&")
	


#-------------------start here-------------------------
#定义变量区
sys.path.append("/usr/local/python35/lib/python3.5/site-packages")
now_time = datetime.datetime.now()
today=now_time.strftime('%Y-%m-%d')
yes_time = now_time + datetime.timedelta(days=-1)
yes_time_nyr = yes_time.strftime('%Y-%m-%d')
sync_list=[]
sync_file="synclist.txt"
if_sync=1	#1,初始,2同步进程存在,正在同步,0同步结束
log_sw=1 	#同步状态变化

try:
	opts, args = getopt.getopt(sys.argv[1:], "hd:") 
except getopt.GetoptError:  
	print("opt error")
for name,value in opts:
	
	if name=="-d":
		yes_time_nyr=value
	if name=="-h":
		usage()
		exit()
r_ip=args[0]
r_name=args[1]
hostmod=r_ip+"_"+r_name
print yes_time_nyr
#数据库连接
try:
	conn=MySQLdb.connect(host='192.168.1.28',user='root',passwd='work',port=3306)
	cur=conn.cursor()
	conn.select_db('work')
except MySQLdb.Error:
	print ("Mysql Error ")



	
todir=config_read.get('rsync',r_ip+"_"+r_name)
is_exists()
start_size=getsize()
logging.info(hostmod+"   start_size   "+start_size)
ready4sync()
do_sync()
time.sleep(60)
while (if_sync>=1):
	check_sync()
	time.sleep(10)

end_size=getsize()
cur.execute('insert into logsize_day values("'+hostmod+'",'+start_size+','+end_size+',"'+today+'");')
logging.info(hostmod+"   endsize   "+end_size)

#数据库关闭
conn.commit()
cur.close()
conn.close()

